#include "data.h"

void Client_Handler(int newfd, struct data_transfer *dt, sqlite3 *db);
int main(int argc, char *argv[]){

	char buf[BUFSIZ] = {};
	struct config conf;
	struct data_transfer *dt = (struct server_response *)buf;
	int newfd;
	sqlite3 *db;
	char *errmsg;
	pid_t pid;

	//1. 初始化服务端IP与port信息
	FT_InitConfig(&conf, "server");

	//2. 准备套接字
	int fd = SocketInit(conf.ip, conf.port, true);

	//3.初始化数据库
	if(sqlite3_open(DATABASE, &db) != SQLITE_OK){
		printf("%s\n", sqlite3_errmsg(db));
		return -1;
	} else{
		printf("open DATABASE success.\n");
	}
	if(sqlite3_exec(db, "create table if not exists stu(id int, name char , sex char , score int);",
				NULL, NULL, &errmsg) != SQLITE_OK){
		printf("%s\n", errmsg);
	} else {
		printf("Create or open table success.\n");
	}

	//4.循环响应客户端请求
	while(1)
	{
		newfd = accept(fd, NULL, NULL);
		if(newfd < 0){
			perror("accept");
			exit(0);
		}
		pid = fork();
		if(pid < 0){
			perror("fork");
			return -1;
		}else if(pid == 0){
			close(fd);
			Client_Handler(newfd, dt, db);
		}else{
			close(newfd);
		}
	}

	close(fd);
	return 0;
}

void Client_Handler(int newfd, struct data_transfer *dt, sqlite3 *db){
	while(Read(newfd, dt, SIZE_DT_TYPE) > 0){
		switch(dt -> type){
			//新增数据
		case TYPE_INSERT:
			do_insert_handler(newfd, dt, db);
			break;
			//查询数据
		case TYPE_QUERY:
			do_query_handler(newfd, dt, db);
			break;
			//更新数据
		case TYPE_UPDATE:
			do_update_handler(newfd, dt, db);
			//删除数据
		case TYPE_DELETE:
			do_delete_handler(newfd, dt, db);
		}
	}
}
